function [encodedBits,alpha]=WiSiL_Encoder_turboEncoder(bitsTx,encoder)
% TURBOENCODER - Performs the turbo encoding
%
%   [encodedBits,alpha] = TurboEncoder(bitsTx,encoder)
%     This function implements the turbo encoder scheme defined  
%     by 36.212. The interleaver map is
%     Trellis Termination is performed according to described at 36.212
%     V8.2.0
%     The interleaver is pseudo-random and it is not adequated to 36.212.
%
%   Input parameters:
%     bitsTx : The bits related to a frame that is going to be transmitted
%     encoder : Struct containing the field encoder.tcPoly, which is the
%     polynomial generator for the Turbo Encoder.
%
%   Output parameters:
%     encodedBits : The bits related to a frame after the turbo encoding process
%     alpha           : Index of the interleaved bits  (used for the deinterleaver)
%
% History:
% Rafhael Medeiros de Amorim ( rma.petit@gmail.com )
% July 30th, 2008.



WiSiL_Encoder_interleaverTable; % Interleaver table (36.212) - Used to calculate the interleaved sequence
                    % to the second convolutiona encoder.
                    
Ki = length(bitsTx);   % Ki index - See 36.212 for more information. 
index = find (K == Ki); % Find Ki at interleaver table

%-- Dealing with null values. -- 
    auxiliar = isnan(bitsTx); 
    temp = find(auxiliar == 1);
    bitsTx(temp) = 0;
%--         ---               --     

%-- Interleaved Sequence      --
    alpha(1,:) = mod((1:Ki)*f1(index)+(1:Ki).^2*f2(index),Ki);  
    alpha(1,:) = alpha+1;
%--         ---               --

% Set Encoder Parameters
constraint = 4; %Constraint length 
feedback = encoder.TurboCoding.feedback;   %Feedback polynomial used at Turbo Coding
poly = encoder.TurboCoding.poly;          %Generator polynomials 
trellis = poly2trellis(constraint,poly,feedback); % Trellis

% Initialization of matrices
encodedBits = zeros(3, length(bitsTx) );


[auxiliar, state(1)] = convenc(bitsTx,trellis); %First convolutional encoder.
[auxiliar2, state(2)] = convenc(bitsTx(alpha),trellis); %Second convolutional encoder.
encoded(1,:) = auxiliar(1:2:end); % Systematic output.
encoded(2,:) = auxiliar(2:2:end); % Parity output (1st encoder)
encoded(3,:) = auxiliar2(2:2:end); %Parity output (2nd encoder)

encoded(:,temp) = []; %Eliminating null values. 

% Trellis Termination 
 encodedBits = WiSiL_Encoder_trellisTermination(encoded,state,constraint);